package com.piece.core.web.interceptor;

import com.piece.core.framework.constant.PermissionConstants;
import com.piece.core.framework.exception.DemoModeException;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.log.client.dto.UserDTO;
import com.piece.core.log.config.UserContextHolder;
import com.piece.core.web.authority.AuthorityFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class DemoInterceptor extends InterceptorHookSupport {

    @Resource
    private AuthorityFactory authorityFactory;

    @Override
    public String[] getInterceptor() {
        return null;
    }

    @Override
    public void preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        boolean isDemo = false;
        String method = handler.getMethod().getName();

        UserDTO user = UserContextHolder.get();
        if (null != user && null != authorityFactory.get()) {
            if (!authorityFactory.get().isPermitted(PermissionConstants.ADMIN_PERMISSION)
                && authorityFactory.get().isPermitted(PermissionConstants.DEMO_PERMISSION)) {
                isDemo = true;
            }
        }

        if (isDemo) {
            if (StringUtil.containsAny(method, new String[]{"save", "update", "delete", "change", "clear", "run", "publish", "upload"})) {
                throw new DemoModeException();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, Exception ex) {
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
    }
}
